package com.ljw.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ljw.common.utils.R;
import com.ljw.gulimall.cart.feign.ProductFeignService;
import com.ljw.gulimall.cart.interceptor.CartInterceptor;
import com.ljw.gulimall.cart.service.CartService;
import com.ljw.gulimall.cart.to.UserInfoTo;
import com.ljw.gulimall.cart.vo.Cart;
import com.ljw.gulimall.cart.vo.CartItem;
import com.ljw.gulimall.cart.vo.SkuInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";


    @Override
    public CartItem addToCart(Long skuId, Integer num) {

        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();
        String cartItemJsonExist = (String) cartOps.get(skuId.toString());
        //添加商品信息到购物车中去
        CartItem cartItem = new CartItem();

        if (StringUtils.isEmpty(cartItemJsonExist)){
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuinfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                if (skuinfo != null) {
                    cartItem.setSkuId(skuinfo.getSkuId());
                    cartItem.setCheck(true);
                    cartItem.setCount(num);
                    cartItem.setImage(skuinfo.getSkuDefaultImg());
                    cartItem.setTitle(skuinfo.getSkuTitle());
                    cartItem.setPrice(skuinfo.getPrice());
                    BigDecimal totalPrice = cartItem.getPrice().multiply(new BigDecimal("" + num));
                    cartItem.setTotalPrice(totalPrice);
                }
            }, executor);

            CompletableFuture<Void> getSkuAttrValuesTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                if (skuSaleAttrValues != null && skuSaleAttrValues.size() > 0){
                    cartItem.setSkuAttr(skuSaleAttrValues);
                }
            }, executor);

            try {
                CompletableFuture.allOf(getSkuInfoTask, getSkuAttrValuesTask).get();
                if (cartItem != null){
                    String cartItemJson = JSON.toJSONString(cartItem);
                    cartOps.put(cartItem.getSkuId().toString(), cartItemJson);
                }
                return cartItem;
            } catch (InterruptedException e) {
                e.printStackTrace();
                return cartItem;
            } catch (ExecutionException e) {
                e.printStackTrace();
                return cartItem;
            }

        }
        else {
            CartItem cartItemExist = JSON.parseObject(cartItemJsonExist, new TypeReference<CartItem>() {
            });
            cartItemExist.setCount(cartItemExist.getCount() + num);
            //现在的总价格为更新后的总数量*单价
            BigDecimal nowTotalPrice = cartItemExist.getPrice().multiply(new BigDecimal("" + cartItemExist.getCount()));
            cartItemExist.setTotalPrice(nowTotalPrice);
            String updateCartItemJson = JSON.toJSONString(cartItemExist);
            cartOps.put(cartItemExist.getSkuId().toString(), updateCartItemJson);
            return cartItemExist;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();
        String cartItemJson = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSONObject.parseObject(cartItemJson, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null){
            //1、登入
            //用户购车的redis键
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //临时用户的redis键
            String userKey = CART_PREFIX + userInfoTo.getUserKey();
            //2、如果临时购物车的数据还没有合并，需要进行合并
            List<CartItem> tempCartItemList = this.getCartItems(userKey);
            if (tempCartItemList != null){
                for (CartItem cartItem : tempCartItemList) {
                    this.addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                //清空临时购物车的是数据
                redisTemplate.delete(userKey);
            }
            //3、查询用户的购物车数据，并放到cart中,此时已经包含了临时购物车的数据
            List<CartItem> cartItemTotalList = this.getCartItems(cartKey);
            cart.setItems(cartItemTotalList);
        }
        else {
            //2、没登入
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的购买项
            List<CartItem> cartItems = this.getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        BigDecimal totalPrice = new BigDecimal("0");
        if (cart.getItems() != null && cart.getItems().size() > 0){
            for (CartItem item : cart.getItems()) {
                if (item.getCheck()){
                    totalPrice = item.getTotalPrice().add(totalPrice);
                }
            }
        }
        cart.setTotalAmount(totalPrice);
        return cart;
    }

    /**
     * 清空购物车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 修改购物车中是否被选中
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();
        CartItem cartItem = this.getCartItem(skuId);
        if (check == 1){
            //1代表选中
            cartItem.setCheck(true);
        }
        else {
            cartItem.setCheck(false);
        }
        //提交修改
        String cartItemJson = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), cartItemJson);
    }

    /**
     * 修改购物项数量
     * @param skuId
     * @param num
     */
    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = this.getCartItem(skuId);
        cartItem.setCount(num);
        cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())));
        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();
        String cartItemJson = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),cartItemJson);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 远程调用，为订单模块服务，获取登入用户购物车已选的购物项
     * @return
     */
    @Override
    public List<CartItem> getCurrentUserItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String userId = userInfoTo.getUserId();
        if (userId == null){
            return null;
        }
        //用户购物项在redis中的键
        String cartKey = CART_PREFIX + userId;
        //调用该类中从数据库中获取购物项的方法
        List<CartItem> cartItems = this.getCartItems(cartKey);
        //封装，只返回用户已勾选的购物项
        List<CartItem> collect = cartItems.stream()
                .filter(CartItem::getCheck)
                .map(cartItem -> {
                    BigDecimal price = productFeignService.getPrice(cartItem.getSkuId());
                    cartItem.setPrice(price);
                    return cartItem;
                })
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps(){
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String userId = userInfoTo.getUserId();
        String userKey = userInfoTo.getUserKey();
        String cartKey = "";
        if (userId != null){
            cartKey = CART_PREFIX + userId;
        }
        else {
            cartKey = CART_PREFIX + userKey;
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0){
            List<CartItem> cartItemList = values.stream().map(cartItem -> {
                String cartItemJson = (String) cartItem;
                return JSON.parseObject(cartItemJson, CartItem.class);
            }).collect(Collectors.toList());
            return cartItemList;
        }
        return null;
    }

}
